<?php
namespace Hphp\Support\Facades;

abstract class Facade
{
    protected static $app;
    protected static $resolvedInstances = [];

    protected abstract static function getFacadeAccessor();
    // protected static function getFacadeAccessor()
    // {
    //     throw new Exception('没有指明facade 指定的实例对象', 500);
    // }

    protected static function resolveFacadeInstance($object)
    {
        // 判断是否为对象
        if (\is_object($object)) {
            return $object;
        }
        // 判断是否之前创建过
        if (isset(static::$resolvedInstances[$object] )) {
            return static::$resolvedInstances[$object];
        }

        //var_dump(static::$app,$object);exit;
        // 解析实例对象
        return static::$resolvedInstances[$object] = static::$app[$object];
        // return static::$resolvedInstances[$object] = app($object);
    }

    public static function getFacadeApplication()
    {
        return static::$app;
    }

    public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }

    /**
     * Set the application instance.
     *
     * @param  \Hphp\Foundation\Application  $app
     * @return void
     */
    public static function setFacadeApplication($app)
    {
        static::$app = $app;
        //var_dump('facade');
    }

    public static function __callStatic($method, $params = [])
    {
        $instance = static::getFacadeRoot();
//        var_dump($instance);
        if (! $instance) {
            throw new \Exception('对不起，没有找到可解析的实例对象，请检查 facade 中的 getFacadeAccessor 方法设置', 500);
        }

        return $instance->$method(...$params);

    }
}